package top.porchwood.jweb.mcsm.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.porchwood.jweb.mcsm.struct.MCSMUserDetails;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @Author 一七年夏
 * @Link https://space.bilibili.com/16869954
 * @Email 2098833867@qq.com
 * @License GNU General Public Liscene 3.0
 * @DateTime 2021-08-01 18:48
 */
@Service
public class MCSMUserDetailService implements UserDetailsService {
    private static final Logger logger = LogManager.getLogger();
    private static MCSMUserDetailService service;

    public static MCSMUserDetailService getInstance() {
        return service;
    }

    final JdbcTemplate jdbc;
    final PasswordEncoder passwordEncoder;

    MCSMUserDetailService(JdbcTemplate template, PasswordEncoder encoder) {
        service = this;
        this.jdbc = template;
        this.passwordEncoder = encoder;
    }


    public JdbcTemplate getJdbc() {
        return jdbc;
    }

    public PasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || username.strip().equals("")) throw new UsernameNotFoundException("用户名不能为空");
        if (username.contains("'")) throw new UsernameNotFoundException("用户名存在异常字符");
        MCSMUserDetails user;
        try {
            if(username.contains("@")) user = MCSMUserDetails.toObject(jdbc.queryForMap("select * from cbmc_user where EMAIL='%s'".formatted(username)));
            else user = MCSMUserDetails.toObject(jdbc.queryForMap("select * from cbmc_user where NAME='%s'".formatted(username)));
        } catch (EmptyResultDataAccessException ignored) {
            throw new UsernameNotFoundException("用户%s不存在".formatted(username));
        } catch (Exception ex) {
            logger.warn(ex);
            throw new UsernameNotFoundException("内部错误");
        }
        return user;
    }

    /**
     * 查找用户
     *
     * @param username 用户名
     * @return 用户，如果为Null，则没找到用户
     */
    @Nullable
    public static MCSMUserDetails findUser(@NonNull String username) {
        try {
            return (MCSMUserDetails) getInstance().loadUserByUsername(username);
        } catch (UsernameNotFoundException ex) {
            return null;
        }
    }
}
